clear all;close all;clc;

I = imread('D:\FPGA\Test photo\num\5.jpg');
Ib =im2bw(I);
% Ib =~Ib;  %黑字白底和黑底白字模板相反

%---------------步骤1：找到字符上下左右边界--------------------- 
[ROW,COL] =size(Ib);
min_x=ROW;
max_x=0;
min_y=COL;
max_y=0;

for i=1:ROW
    for j=1:COL
        if Ib(i,j)==0 
            if(min_x>i)
                min_x = i;
            end
            if(max_x<i)
                max_x = i;
            end
            if(min_y>j)
                min_y = j;
            end
            if(max_y<j)
                max_y = j;
            end
        end
    end
end
 

%--------------- 步骤2：画特征线---------------
height = max_x - min_x;
x1 = round(min_x+height*2/6);
x2 = round(min_x+height*4/5);
width = max_y - min_y;
y = round(min_y + width*1/2);

for i=1:ROW
    for j=1:COL
      if(i >= min_x && i <= max_x)&&(j==min_y ||j==max_y || j==y)
          R(i,j,1)= 255;
          R(i,j,2)= 0;
          R(i,j,3)= 0;
      elseif(i == min_x || i == max_x || i ==x1 || i ==x2)&&(j>=min_y && j<=max_y)
          R(i,j,1)= 255;
          R(i,j,2)= 0;
          R(i,j,3)= 0;
      else
          R(i,j,1)= I(i,j,1);       %I(i,j,1)
          R(i,j,2)= I(i,j,2);
          R(i,j,3)= I(i,j,3);
      end
    end
end

figure;
imshow(R);

%---------------步骤3：统计特征信息---------------------

cross_y=0;
cross_x1_L=0;
cross_x1_R=0;
cross_x2_L=0;
cross_x2_R=0;

for i=1:ROW-1
    for j=1:COL-1
      if j == y && Ib(i,j)==1&&Ib(i+1,j)==0
          cross_y =cross_y+1;
      elseif i == x1 && Ib(i,j)==1&&Ib(i,j+1)==0
          if(j<y)
              cross_x1_L =cross_x1_L+1;
          elseif(j>y)
              cross_x1_R =cross_x1_R+1;
          end
      elseif i == x2 && Ib(i,j)==1&&Ib(i,j+1)==0
          if(j<y)
              cross_x2_L =cross_x2_L+1;
          elseif(j>y)
              cross_x2_R =cross_x2_R+1;
          end
      end
    end
end


%---------------步骤4：根据交点数匹配数字---------------
cross_x1=cross_x1_L+cross_x1_R;
cross_x2=cross_x2_L+cross_x2_R;

result=NaN;

if(cross_y==1)
    if(cross_x1==1 && cross_x2==1)
        result=1;
    end
elseif(cross_y==2)
    if(cross_x1==1 && cross_x2==1)
        result=7;
    elseif(cross_x1==2 && cross_x2==1)
        result=4;
    elseif(cross_x1==2 && cross_x2==2)
        result=0;
    end
elseif(cross_y==3)
    if(cross_x1==1 && cross_x2==2)
        result=6;
    elseif(cross_x1==2 && cross_x2==1)
        result=9;   
    elseif(cross_x1==2 && cross_x2==2)
        result=8;  
    elseif(cross_x1==1 && cross_x2==1)
        if(cross_x1_R==1 && cross_x2_L==1)
            result=2;
        elseif(cross_x1_R==1 && cross_x2_R==1)
            result=3;
        elseif(cross_x1_L==1 && cross_x2_R==1)
            result=5;    
        end
    end
end

display(result);